package com.loie.datacenter.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.loie.datacenter.model.bo.TokenInfoBO;
import com.loie.datacenter.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object arg2) throws Exception {
        httpServletResponse.setCharacterEncoding("UTF-8");
        String token = httpServletRequest.getHeader("Authorization");
        if (null == token) {
            Map<String, Object> map = new HashMap<>(3);
            map.put("data", "token is null");
            map.put("errorCode", "401");
            map.put("success", false);
            map.put("errorMessage", "认证超时或者禁示访问，请重新登录");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
        } else {
            TokenInfoBO tokenInfoBO = new TokenInfoBO();
            tokenInfoBO.setToken(token);
            boolean result = TokenUtils.verify(tokenInfoBO);
            if (result) {
                httpServletRequest.getSession().setAttribute("currentUser", tokenInfoBO);
                return true;
            }
            Map<String, Object> map = new HashMap<>(2);
            map.put("data", "token is null");
            map.put("errorCode", "401");
            map.put("success", false);
            map.put("errorMessage", "认证超时或者禁示访问，请重新登录");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpServletResponse.getWriter().write(JSONObject.toJSONString(map));
        }
        return false;

    }
}
